package lancoo.com.net.errorhandlers;

import android.accounts.NetworkErrorException;
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;


import java.lang.ref.WeakReference;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.Observer;
import io.reactivex.Single;
import io.reactivex.SingleOnSubscribe;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import lancoo.com.net.HttpErrors;

/**
 * @param <T>
 * @author John
 */
public class TokenExpiredNotCallBackHandler<T> implements ObservableTransformer<T, T> {

    private WeakReference<Context> mWeakReference;
    private boolean hasTokenAlive;

    public TokenExpiredNotCallBackHandler(Context context) {
        mWeakReference = new WeakReference<>(context);
        hasTokenAlive=false;
    }

    @Override
    public ObservableSource<T> apply(Observable<T> upstream) {
        return upstream
                .startWith(new ObservableSource<T>() {
                    @Override
                    public void subscribe(Observer<? super T> observer) {
                        Context context = mWeakReference.get();
                        if (context == null) {
                            Log.e("rrrr", "完了。。。onComplete1111:"+observer.toString());
                            observer.onComplete();
                        } else {
                            if(hasTokenAlive){
                                observer.onComplete();
                            }else{
                                Log.e("rrrr", "完了。。。onComplete1111:"+observer.toString());
                                observer.onError(new HttpErrors.TokenExpiredError());
                            }
                        }
                    }
                })
                .retryWhen(new Function<Observable<Throwable>, ObservableSource<?>>() {
                    @Override
                    public ObservableSource<?> apply(Observable<Throwable> throwableObservable) throws Exception {
                        return throwableObservable.flatMap(throwable -> {

                            if(throwable instanceof NetworkErrorException){
                                return Observable.error(throwable);
                            }
                            Log.e("token error","throwable:"+throwable.toString());
                            return Single.create((SingleOnSubscribe<Boolean>) emitter -> {
                                Context context = mWeakReference.get();
                                if (context == null || !(throwable instanceof HttpErrors.TokenExpiredError)) {
                                    Log.e("rrrr", "完了。。。onSuccess");
                                    emitter.onSuccess(false);
                                    return;
                                }

                            })
                                    .observeOn(Schedulers.io())
                                    .flatMapObservable((Function<Boolean, ObservableSource<?>>) reLogin -> {

                                        if (reLogin) {
                                            Log.e("rrrr", "完了。。。just");
                                            return Observable.just(-1);
//                                           return Observable.timer(200, TimeUnit.MILLISECONDS);
                                        } else {
                                            Log.e("rrrr", "完了。。。error");
                                            return Observable.error(throwable);
                                        }
                                    });
                        });
                    }
                });
    }


}
